package com.app.configuration.web.mvc;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import com.app.util.common.DataConvertFactory;

/**
 * 数据转换配置，针对controller中接收对象的属性类型为Date，Double，和int时，自动将非匹配参数值自动转换成该类型的默认值
 * 如Date类型，如参数值为非Date格式，则转为null，double和int则转为0.0和0
 * @author chenl
 *
 */
@Configuration
public class WebMvcDataConvertConfiguration {

	@Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();
            genericConversionService.addConverter(DataConvertFactory.getDateConvert());
            genericConversionService.addConverter(DataConvertFactory.getIntegerConvert());
            genericConversionService.addConverter(DataConvertFactory.getDoubleConvert());
            genericConversionService.addConverter(DataConvertFactory.getFloatConvert());
        }
    }
}
